//main
import React, { useContext } from "react";
import { connect } from "react-redux";
import { ThemeProvider } from "@material-ui/core";
//data
import Context from "../../Context.js";
//styles
import { useStyles } from "./ChatSpace.jss";
//funcs
import { dec } from "../../func/chatList/chat.js";

function Message(props) {
  const { theme, currentChat } = useContext(Context);
  const classes = useStyles(theme);

  if (currentChat) {
    return Object.keys(props.chats[currentChat].messages).map((key, index) => {
      var date = new Date(
        props.chats[currentChat].messages[key].timestamp * 1000
      );
      var image = dec(
        props.chats[currentChat].messages[key].image,
        props.chats[currentChat].key
      );

      function Image() {
        if (image != "") {
          return <img src={image} className={classes.messageImage} />;
        } else {
          return <></>;
        }
      }

      return (
        <ThemeProvider theme={theme} key={key}>
          <div className={classes.message}>
            <div className={classes.messageInfoBox}>
              <div className={classes.messageInfoBoxName}>
                {props.chats[currentChat].messages[key].senderName}
              </div>
              <div className={classes.messageInfoBoxDate}>
                {date.getHours()}:{date.getMinutes()} | {date.getDate()}.
                {date.getMonth() + 1}.{date.getFullYear()}
              </div>
            </div>
            <div className={classes.messageText}>
              {dec(
                props.chats[currentChat].messages[key].message,
                props.chats[currentChat].key
              )}
            </div>
            <Image />
          </div>
        </ThemeProvider>
      );
    });
  } else {
    return <></>;
  }
}

const mapStateToProps = (state) => {
  return {
    chats: state.chats,
  };
};

export default connect(mapStateToProps, null)(Message);
